package com.sihan.framework.etm.common;

import com.framework.mybatis.Condition;
import com.sihan.framework.etm.entity.User;
import com.sihan.framework.etm.mapper.UserMapper;
import com.sihan.framework.etm.service.PermissionService;
import com.sihan.framework.etm.service.RoleService;
import com.sihan.framework.etm.service.UserService;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

public class ShiroRealm extends AuthorizingRealm {

  @Lazy
  @Autowired
  private UserService userService;
  
  @Lazy
  @Autowired
  private UserMapper userMapper;

  @Lazy
  @Autowired
  private RoleService roleService;

  @Lazy
  @Autowired
  private PermissionService permissionService;

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    String username = (String) principals.getPrimaryPrincipal();
    //添加角色
    Set<String> roles = roleService.selectRolesByUsername(username);
    if (CollectionUtils.isNotEmpty(roles)) {
      info.addRoles(roles);
      //添加权限
      Set<String> permissions = permissionService.selectPermissionsByRoles(roles);
      if (CollectionUtils.isNotEmpty(permissions)) {
        info.addStringPermissions(permissions);
      }
    }
    return info;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    String username = (String) token.getPrincipal();
    //User user = userService.selectOne(new Condition<>(new User(username, false)));
    User user = userMapper.selectOne(new Condition<>().eq("username", username).eq("is_delete", 0));
    if (user == null) {
      throw new UnknownAccountException();
    } else if (user.getLocked() != null && user.getLocked()) {
      throw new LockedAccountException();
    }

    return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
  }

}
